<template>
  <!--  :close-on-click-modal="false"-->
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="70%">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <!--      <el-form-item label="门店编号" prop="storeId">-->
      <!--        <el-input v-model="formData.storeId" placeholder="请输入门店编号" />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="订单类型" prop="orderType">-->
      <!--        <el-radio-group v-model="formData.orderType">-->
      <!--          <el-radio-->
      <!--            v-for="dict in getIntDictOptions(DICT_TYPE.DISPATCH_ORDER_TYPE)"-->
      <!--            :key="dict.value"-->
      <!--            :label="dict.value"-->
      <!--          >-->
      <!--            {{ dict.label }}-->
      <!--          </el-radio>-->
      <!--        </el-radio-group>-->
      <!--      </el-form-item>-->
      <el-row>
        <el-col :span="8">
          <el-form-item label="渠道客户" prop="orderType" label-width="80">
            <el-select
              v-model="formData.orderType"
              placeholder="请选择渠道客户"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.DISPATCH_ORDER_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="车牌" prop="licensePlate" label-width="80">
            <el-input class="!w-200px" clearable v-model="formData.licensePlate" placeholder="请输入车牌"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="车主" prop="customerName" label-width="80">
            <el-input class="!w-200px" clearable v-model="formData.customerName" placeholder="请输入客户名称"/>
          </el-form-item>
        </el-col>
      </el-row>


      <!--      <el-form-item label="品牌" prop="glassBrand" label-width="80">-->
      <!--        <el-select v-model="formData.brandId"  class="!w-200px"-->
      <!--                   placeholder="请选择品牌" clearable>-->
      <!--          <el-option-->
      <!--            v-for="dict in getIntDictOptions(DICT_TYPE.ERP_GLASS_BRAND)"-->
      <!--            :key="dict.value"-->
      <!--            :label="dict.label"-->
      <!--            :value="dict.value"-->
      <!--          />-->
      <!--        </el-select>-->
      <!--      </el-form-item>-->

      <!--      <el-form-item label="业务类型" prop="saleType" label-width="80">-->
      <!--        <el-select v-model="formData.saleType"  class="!w-200px"-->
      <!--                   placeholder="请选择业务类型" clearable>-->
      <!--          <el-option-->
      <!--            v-for="dict in getIntDictOptions(DICT_TYPE.ERP_SALE_TYPE)"-->
      <!--            :key="dict.value"-->
      <!--            :label="dict.label"-->
      <!--            :value="dict.value"-->
      <!--          />-->
      <!--        </el-select>-->
      <!--      </el-form-item>-->

      <el-row>
        <el-col :span="9">
          <el-form-item label="车主地址" prop="customerAddrress" label-width="80">
            <el-input class="!w-200px" clearable v-model="formData.customerAddrress"
                      placeholder="请输入车主地址信息"/>
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="车主手机" prop="telephone" label-width="80">
            <el-input clearable class="!w-200px" v-model="formData.telephone" placeholder="车主手机号"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="开启" prop="status" label-width="80">
            <el-radio-group v-model="formData.status">
              <el-radio
                v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
                :key="dict.value"
                :label="dict.value"
              >
                {{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>


      <!--      <el-form-item label="VIN" prop="vin" label-width="80">-->
      <!--        <el-input-->
      <!--          class="!w-320px"-->
      <!--          v-model="formData.vin"-->
      <!--          style="max-width: 600px"-->
      <!--          placeholder="请输入VIN"-->
      <!--        >-->
      <!--          <template #append>-->
      <!--            <el-button @click="handleJyCarTypeByVin" type="success">搜索车型</el-button>-->
      <!--          </template>-->
      <!--        </el-input>-->
      <!--      </el-form-item>-->
      <!--      -->
      <!--      <el-form-item label="车型" prop="carType" label-width="80">-->
      <!--        <el-input  class="!w-200px" v-model="formData.carType" placeholder="请输入车型" />-->
      <!--      </el-form-item>-->
      <el-row>
        <el-col :span="24">
          <ContentWrap>
            <el-tabs v-model="subTabsName" class="-mt-15px -mb-10px">
              <el-tab-pane label="选择产品" name="item">
                <GetProductForm ref="itemFormRef" :items="formData.items"
                                :disabled="disabled"/>
              </el-tab-pane>
            </el-tabs>
          </ContentWrap>
        </el-col>
      </el-row>
      <!--      </el-form-item>-->

<!--      <el-form-item label="订单价格" prop="orderPrice" label-width="80">-->
<!--        <el-input class="!w-200px" v-model="formData.orderPrice" placeholder="请输入订单价格"/>-->
<!--      </el-form-item>-->
<!--      <el-form-item label="派单价格" prop="orderPrice" label-width="80">-->
<!--        <el-input class="!w-200px" v-model="formData.dispatchPrice" placeholder="请输入派单价格"/>-->
<!--      </el-form-item>-->

<!--      <el-form-item label="" prop="remark" label-width="80">-->
        <el-input rows="2" type="textarea" show-word-limit maxlength="200" v-model="formData.remark"
                  placeholder="请输入备注"/>
<!--      </el-form-item>-->
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import {getIntDictOptions, DICT_TYPE} from '@/utils/dict'
import {OrderApi, OrderVO} from '@/api/dispatch/order'
import {ElLoading, ElMessage} from "element-plus";
import {SaleOrderApi} from "@/api/erp/sale/order";
import SaleOrderItemForm from '../../erp/sale/order/components/SaleOrderItemForm.vue'
import GetProductForm from "../../erp/sale/order/components/GetProductForm.vue";
import {ref} from "vue";

/** 派单系统 订单 表单 */
defineOptions({name: 'OrderForm'})

const itemFormRef = ref(null);

const {t} = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const productFormRef = ref() //产品信息
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  storeId: undefined,
  orderType: undefined,
  brandId: undefined,
  saleType: undefined,
  licensePlate: undefined,
  telephone: undefined,
  vin: undefined,
  remark: undefined,
  items: [],
  carTypeName: undefined,
  productList:[],
  status: 1,
  productId: undefined,
  sort: 1,
  carType: undefined,
  customerName: undefined,
  customerAddrress: undefined,
  orderPrice: undefined,
  dispatchPrice: undefined
})


const formRules = reactive({
  licensePlate: [{required: true, message: '车牌不能为空', trigger: 'blur'}],
  orderType: [{required: true, message: '渠道客户不能为空', trigger: 'blur'}]
})
const formRef = ref() // 表单 Ref
/** 子表的表单 */
const subTabsName = ref('item')
//根据vin获取车型
// const handleJyCarTypeByVin = async () => {
//   const vinVal = formData.value.vin;
//   if (vinVal == undefined || vinVal.length != 17) {
//     ElMessage.error('请输入正确的17位VIN');
//     return;
//   }
//
//   const loading = ElLoading.service({
//     lock: true,
//     text: '车型查询中...',
//     background: 'rgba(0, 0, 0, 0.7)',
//   })
//
//   const data = await SaleOrderApi.getJyCarTypeByVin(vinVal);
//
//
//   if (data == null) {
//     formData.value.carType = undefined;
//     formData.value.productType = undefined;
//     formData.value.amVehicleId = undefined;
//     formData.value.amMainBrandName = undefined;
//     formData.value.amBrandName = undefined;
//     formData.value.amSeriesName = undefined;
//     formData.value.amSeriesId = undefined;
//     formData.value.amVehicleName = undefined;
//     ElMessage.error('未查询到车型信息,请检查VIN是否正确');
//   } else {
//     //车型
//     formData.value.carType = data.amBrandName + data.amSeriesName + '-' + data.amYear + '款';
//
//     formData.value.amVehicleId = data.amVehicleId;
//     formData.value.amMainBrandName = data.amMainBrandName;
//     formData.value.amBrandName = data.amBrandName;
//     formData.value.amSeriesName = data.amSeriesName;
//     formData.value.amSeriesId = data.amSeriesId;
//     formData.value.amVehicleName = data.amVehicleName;
//     formData.value.amYear = data.amYear;
//   }
//   setTimeout(() => {
//     loading.close()
//   }, 500)
// }


//监听formData.items
watch(
  () => formData.value.items,
  (newVal) => {
    if (newVal.length > 0) {
        console.log(newVal)
    }
  }
)

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await OrderApi.getOrder(id)
      formData.value.items = [
        {
          productId: formData.value.productId,
          orderPrice: formData.value.orderPrice,
          dispatchPrice: formData.value.dispatchPrice,
          productList:formData.value.productList
        }
      ]
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({open}) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {

  if(formData.value.items.length==0){
    ElMessage.error('请选择产品');
  }
  if(formData.value.items[0].productId==undefined||formData.value.items[0].productId.length==0){
    ElMessage.error('请选择产品');
    return;
  }
  //获取产品信息
  formData.value.productId = formData.value.items[0].productId;
  formData.value.orderPrice = formData.value.items[0].orderPrice;
  formData.value.dispatchPrice = formData.value.items[0].dispatchPrice;
  //获取车型
  formData.value.carType = itemFormRef.value.carTypeName;
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as OrderVO
    if (formType.value === 'create') {
      await OrderApi.createOrder(data)
      message.success(t('提交成功'))
    } else {
      await OrderApi.updateOrder(data)
      message.success(t('处理成功'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  //重置formData
  formData.value = {
    storeId: undefined,
    orderType: undefined,
    brandId: undefined,
    saleType: undefined,
    licensePlate: undefined,
    items: [],
    telephone: undefined,
    vin: undefined,
    remark: undefined,
    productId:undefined,
    status: undefined,
    sort: 1,
    carType: undefined,
    customerName: undefined,
    customerAddrress: undefined,
    orderPrice: undefined,
    dispatchPrice: undefined
  };
  formRef.value?.resetFields()
}
</script>
